package com.example.itemtouchhelper

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.itemtouchhelper.entity.Bean
import java.util.*

/**
 * @author by liliang on 2020/6/2 1:39 AM
 */
class RecyclerViewAdapter(private var beans: MutableList<Bean>, private var context: Context) :
    RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>(), ItemTouchState {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var textView: TextView = view.findViewById(R.id.textView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =
            LayoutInflater.from(context)
                .inflate(R.layout.item_recycler_view, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = beans.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.textView.text = beans[position].name
        holder.itemView.setBackgroundColor(beans[position].color)
    }

    override fun onItemMove(position: Int, toPosition: Int): Boolean {
        Collections.swap(beans, position, toPosition)
        notifyItemMoved(position, toPosition)
        return true
    }

    override fun onItemRemove(position: Int): Boolean {
        beans.removeAt(position)
        notifyItemRemoved(position)
        return true
    }
}